//
//  YSPHomeController.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/15.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVPullToRefresh
enum ReuseIdentifier: String {
    case ForwardCellReuseIdentifier = "ForwardCellReuseIdentifier"
    case OriginalCellReuseIdentifier = "OriginalCellReuseIdentifier"
}

class YSPHomeController: YSPBaseViewController {
    
    var statusModelArray: [YSPStatus]? {
        didSet {
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if !YSPUserAccount.userLogin {
            return
        }
        prepareTableView()
        
        refreshControl = YSPRefreshViewController()
        
        refreshControl?.tintColor = UIColor.whiteColor()
        
        refreshControl?.addTarget(self, action: "loadNewData", forControlEvents: UIControlEvents.ValueChanged)
        
        //这个方法会让refresh的view显示出来，但不会主动出发valuechanged事件
        refreshControl?.beginRefreshing()
        
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    func prepareTableView() {
        tableView.registerClass(YSPOriginalCell.self, forCellReuseIdentifier: ReuseIdentifier.OriginalCellReuseIdentifier.rawValue)
        tableView.registerClass(YSPForwardCell.self, forCellReuseIdentifier: ReuseIdentifier.ForwardCellReuseIdentifier.rawValue)
        // 设置cell预估行高
        /*
        使用预估行高,不会一次性将所有cell的行高都计算出来,计算的个数根预估行高和cell实际行高有关
        预估200,算了4个cell 667 / 200 = 3.x(4),cell也正好够高度,当预估的高度算好后,cell不够显示,在计算一个.直到屏幕上完全显示cell为止,预估行高不能太小,尽量准确
        */
        tableView.rowHeight = 200
        //        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        setupNavigationBar()
        
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreData()
        }
    }
    
    func loadNewData() {
        let since_id = statusModelArray?.first?.id ?? 0
        let max_id = 0
        YSPStatus.loadStatus(since_id, max_id: max_id) { (statusArray, error) -> () in
            
            self.refreshControl?.endRefreshing()
            if error != nil {
                return
            }
            
            let count = statusArray?.count ?? 0
            if count == 0 {
                print("没有加载到数据")
                return
            }
            
            if since_id > 0 {
                //已经有了数据，下拉刷新后拼接新的数据在原有数据的前面
                self.statusModelArray = statusArray! + self.statusModelArray!
            } else {
                //第一次进入程序
                self.statusModelArray = statusArray
            }
            
        }
//        print("完成加载数据")
    }
    
    func loadMoreData() {
        let since_id = 0
        let max_id = statusModelArray?.last?.id ?? 0
        YSPStatus.loadStatus(since_id, max_id: max_id) { (statusArray, error) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil {
                return
            }
            
            let count = statusArray?.count ?? 0
            if count == 0 {
                print("没有加载到数据")
                return
            }
            
            if max_id > 0 {
                //已经有了数据，下拉刷新后拼接新的数据在原有数据的前面
                self.statusModelArray = self.statusModelArray! + statusArray!
            }
        }
    }
    
    private func setupNavigationBar() {
        //设置左边按钮
//        let leftBarButton = UIButton()
//        leftBarButton.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
//        leftBarButton.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
//        leftBarButton.sizeToFit()
//        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButton("navigationbar_friendsearch")
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName:"navigationbar_friendsearch")
        //设置右边按钮
//        let rightBarButton = UIButton()
//        rightBarButton.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
//        rightBarButton.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
//        rightBarButton.sizeToFit()
//        navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButton("navigationbar_pop")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        let navigationTitle = YSPUserAccount.userAccount?.screen_name ?? "首页"
        navigationItem.titleView = YSPCustomButton.init(imageName: "navigationbar_arrow_down", title: navigationTitle)
    }
    
    //MARK: - 数据源方法
    
    //返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //取出当前的模型
        let statusModel = statusModelArray![indexPath.row]
        //如果模型有行高的缓存，直接返回
        if statusModel.rowHeight != nil {
            return statusModel.rowHeight!
        }
        
        //模型没有行高的缓存，通过cell的方法来取
        let cellType = statusModel.getCellType()
        let cell = tableView.dequeueReusableCellWithIdentifier(cellType) as! YSPStatusCell
        let rowHeight = cell.getRowHeightOfCell(statusModel)
        
        statusModel.rowHeight = rowHeight
        
        return rowHeight
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusModelArray?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let statusModel = statusModelArray![indexPath.row]
        let cellType = statusModel.getCellType()
        let cell = tableView.dequeueReusableCellWithIdentifier(cellType)! as! YSPStatusCell
        
        cell.statusModel = statusModel
        
        
        return cell
    }
    
    
    
    
    
    
    
    
    
    
    
    
}
